package com.hjw.httpclient.demo;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 使用JDK原生的api发送网页请求
 * @author hjwStrart
 * @time 2022-11-08 20:00
 * @version: 1.0
 */
public class Demo1 {

    @Test
    public void method1() throws Exception {
        String urlStr = "https://www.baidu.com/";
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        // 设置 urlConnection 的请求方式
        urlConnection.setRequestMethod("GET"); // GET、POST、PUT、DELETE...
//        urlConnection.setRequestProperty(); // 设置请求头属性

        // 获取 HttpURLConnection 的输入流
        InputStream is = urlConnection.getInputStream();
        // 将字节流转换为字符流  （方便操作）
        InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
        // 将字符流转换为 缓存字符流 进一步提高读取效率
        BufferedReader br = new BufferedReader(isr);

        String line;  // 用来接收 br 每次按行读取的 结果
        StringBuilder sb = new StringBuilder();

        while((line = br.readLine()) != null){
            sb.append(line + "\n");
        }
        // 输出 http://www.baidu.com 的源码
        System.out.println(sb.toString());

    }
}
